<template>
  <form class="row g-3 needs-validation">
    <slot />
  </form>
</template>
<script>
import { provide, onUnmounted } from 'vue';
import bus from './bus';
export default {
  name: 'MForm',
  props: {
    model: {
      type: Object,
      required: true,
    },
    rules: Object,
  },
  setup(props) {
    provide('form', props);
    const fields = [];
    // 全局校验
    const validate = (cb) => {
      const tasks = fields.map((item) => item());
      Promise.all(tasks)
        .then(() => cb(true))
        .catch(() => cb(false));
    };

    bus.$on('form-addfield', (data) => {
      fields.push(data);
    });

    onUnmounted(() => {
      bus.$off('form-addfield');
    });
    return {
      props,
      validate,
    };
  },
};
</script>
